#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/nginx-vhosts/functions"
source "$PLUGIN_AVAILABLE_PATH/letsencrypt/functions"
source "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/config"

letsencrypt_acme_revoke () {
  #shellcheck disable=SC2034
  declare desc="perform actual certificate revocation"
  local app="$1"

  letsencrypt_create_root "$app"

  dokku_log_info1 "Revoking letsencrypt certificate for ${app}..."

  # read simp_le arguments from appropriate config file into the config array
  local config_dir="$(letsencrypt_configure_and_get_dir "$app")"
  read -r -a config < "$config_dir/config"

  # run letsencrypt as a docker container using "certonly" mode
  # port 80 of the standalone webserver will be forwarded by the proxy
  set +e
  docker run --rm \
    -v "$config_dir:/certs" \
    "${PLUGIN_IMAGE}:${PLUGIN_IMAGE_VERSION}" \
    -f account_key.json \
    -f account_reg.json \
    -f fullchain.pem -f chain.pem -f cert.pem -f key.pem \
    --revoke \
    "${config[@]}"

  local simple_result=$?
  set -e

  # handle simp_le return codes
  # see https://github.com/kuba/simp_le/blob/master/README.rst#manifest
  if [[ $simple_result == 0 ]]; then
    # certificate revoked
    dokku_log_info1 "Certificate revoked successfully."

  else
    # error - don't try to link certificates
    dokku_log_info1 "Certificate revocation failed (code $simple_result)!"
    return

  fi

  # move revoked certificates away
  mv -f "$config_dir/fullchain.pem" "$config_dir/fullchain.pem.revoked" 
  mv -f "$config_dir/chain.pem" "$config_dir/chain.pem.revoked"
  mv -f "$config_dir/cert.pem" "$config_dir/cert.pem.revoked"
  mv -f "$config_dir/key.pem" "$config_dir/key.pem.revoked"

  # removing the certificate will automatically reconfigure nginx
  if [[ -z $DOKKU_APP_NAME ]]; then
    dokku certs:remove "$app"
  else
    dokku certs:remove
  fi

}

letsencrypt_revoke_cmd() {
  #shellcheck disable=SC2034
  declare desc="Revoke a certificate"
  local cmd="letsencrypt:revoke"

  # Support --app/$DOKKU_APP_NAME flag by reordering args into "$cmd $DOKKU_APP_NAME $@"
  local argv=("$@")
  [[ ${argv[0]} == "$cmd" ]] && shift 1
  [[ ! -z $DOKKU_APP_NAME ]] && set -- $DOKKU_APP_NAME $@
  set -- $cmd $@
  ##

  local app="$2"

  [[ -z $app ]] && echo "Please specify an app to run the command on" && exit 1

  dokku_log_info2 "Revoke Let's Encrypt certificate from ${app}..."

  letsencrypt_check_email "$app"
  letsencrypt_update
  letsencrypt_acme_revoke "$app" || true

  dokku_log_verbose "done"
}

letsencrypt_revoke_cmd "$@"
